<template>
	<div class="app-container">
		<jk-operation-card ref="box1" class="margin-bottom-10">
			<div class="flex-between-center-wrap">
				<div class="flex-start-center-wrap">
					<jk-add-button :permission-prefix="prefix" class="margin-5-0 item-gap" @click="onAddBtn"></jk-add-button>
				</div>
				<div class="flex-end-center-wrap">
					<jk-select v-model="searchParams.auditState" :option-list="auditStateList" placeholder="状态" clearable size="small" class="search-bar-item-size1 margin-5-0 item-gap"></jk-select>
					<jk-date-picker v-model="searchParams.belongDate" type="daterange" placeholder="下达日期" size="small" class="search-bar-item-size4 margin-5-0 item-gap" clearable />
					<!--					<jk-date-picker v-model="searchParams.changeDate" type="daterange" :placeholder="searchParams.type === 1 ? '返工日期' : '改包装日期'" size="small" class="search-bar-item-size4 margin-5-0 item-gap" clearable />-->
					<jk-search-input v-model="searchParams.productNameOrCode" placeholder="品种名称或编号" size="small" class="search-bar-item-size2 margin-5-0 item-gap" clearable @on-enter="onSearchBtn" />
					<jk-search-input v-model="searchParams.batchCode" placeholder="批号" size="small" class="search-bar-item-size2 margin-5-0 item-gap" clearable @on-enter="onSearchBtn" />
					<jk-search-input v-model="searchParams.code" placeholder="单据编号" size="small" class="search-bar-item-size2 margin-5-0 item-gap" clearable @on-enter="onSearchBtn" />
					<jk-search-button @click="onSearchBtn"></jk-search-button>
				</div>
			</div>
		</jk-operation-card>

		<jk-card>
			<jk-table :loading="tableLoading" :data="tableData" :height="tableHeight + 20">
				<vxe-column
					v-for="(item, index) in tableColumnList"
					:key="index"
					:title="item.title"
					:align="item.align"
					:field="item.keyName"
					:sortable="item.sortable"
					:fixed="item.fixed ? item.fixed : ''"
					:min-width="item.minWidth"
					:width="item.width"
				>
					<template slot-scope="scope">
						<jk-state-bar v-if="item.keyName === 'auditState'" :state-list="auditStateList" :state="scope.row.auditState"></jk-state-bar>
						<div v-else-if="item.keyName === 'paperTubeList'" :span="4">{{ filterColor(scope.row.paperTubeList || []) }}</div>
						<div v-else-if="item.keyName === 'waistPopeList'" :span="4">{{ filterColor(scope.row.waistPopeList || []) }}</div>
						<div v-else-if="item.keyName === 'labelColorList'" :span="4">{{ filterColor(scope.row.labelColorList || []) }}</div>
						<span v-else>{{ scope.row[item.keyName] }}</span>
					</template>
				</vxe-column>
				<vxe-column title="操作" align="center" fixed="right" :width="250">
					<template slot-scope="scope">
						<div class="flex-center">
							<jk-button :disabled="!getPermission([`${prefix}:update`])" :style="{'text-decoration': getPermission([`${prefix}:update`]) ? '' : 'line-through'}" class="item-gap" size="mini" :type="scope.row.auditState === 2 ? 'warning' : 'success'" :permission-prefix="prefix" @click="onEnableBtn(scope.row)">{{ scope.row.auditState === 0 ? '下发' : scope.row.auditState === 1 ? '完成' : '撤销完成' }}</jk-button>
							<jk-edit-button class="item-gap" :permission-prefix="prefix" :disabled="scope.row.auditState === 2" @click="onEditBtn(scope.row)"></jk-edit-button>
							<el-dropdown @command="onDropdownChange($event, scope.row)">
								<jk-button type="primary" size="mini">
									更多<i class="el-icon-arrow-down el-icon--right"></i>
								</jk-button>
								<el-dropdown-menu slot="dropdown">
									<el-dropdown-item
										v-for="(item, index) in dropdownOption"
										:key="index"
										:style="{'text-decoration': getPermission([`${prefix}:${item.permissionName}`]) ? '' : 'line-through'}"
										:command="item.permissionName"
										:disabled="item.allowState === -1 ? false : scope.row.auditState !== item.allowState"
									>
										<span :class="[item.icon, 'item-gap']"></span>
										<span>{{ item.name }}</span>
									</el-dropdown-item>
								</el-dropdown-menu>
							</el-dropdown>
						</div>
					</template>
				</vxe-column>
			</jk-table>

			<!-- 分页组件 -->
			<footer ref="box2" class="flex-end-center margin-top-10">
				<jk-page
					:page-index="searchParams.pageNo"
					:page-sizes="searchParams.pageSizes"
					:page-size="searchParams.pageSize"
					:total="totalCount"
					@on-change="onPageChange"
				/>
			</footer>
		</jk-card>
		<save-dialog
			:page-type="pageType"
			:data-id="dataId"
			:dialog-state="saveDialogState"
			@on-visible-change="onVisibleChange"
			@on-finish="onFinish"
		></save-dialog>
	</div>
</template>

<script>
    import saveDialog from './save-dialog';
    import calHeight from '/src/mixins/cal-table-height';
    import { pageConfig, tipsBar } from '/src/utils/jk/jk-tool';
    import getMenuColumn from '../../../mixins/getMenuColumn';
    import {
        productionChangeProductRecordClearClose,
        productionChangeProductRecordClose,
        productionChangeProductRecordConfirm,
        productionChangeProductRecordDelete,
        productionChangeProductRecordPage
    } from '../../../api/production/xsNotice';
    import permissionMixin from '../../../mixins/permission-mixin';

    export default {
        name: 'PackageReport',
        components: {
            saveDialog
        },
        mixins: [calHeight, getMenuColumn, permissionMixin],
        data() {
            return {
                apiItem: {
                    'page': productionChangeProductRecordPage
                },
                dropdownOption: [
                    { name: '详情', icon: 'el-icon-view', permissionName: 'query', allowState: -1 },
                    { name: '删除', icon: 'el-icon-delete', permissionName: 'delete', allowState: 1, divided: true }
                ],
                pageType: '',
                prefix: 'production:changeProductRecord',
                auditStateList: [
                    { id: 0, name: '待下发', color: '#ff9900' },
                    { id: 1, name: '已下发', color: '#2d8cf0' },
                    { id: 2, name: '已完成', color: '#0bab5b' }
                ],
                shiftList: [],
                dataId: null,
                workshopList: [],
                saveDialogState: false,
                tableLoading: true,
                exportLoading: false,
                tableData: [],
                totalCount: 0,
                searchParams: {
                    pageNo: pageConfig.pageNo,
                    pageSize: pageConfig.pageSize,
                    changeDate: [],
                    belongDate: [],
                    productNameOrCode: null,
                    batchCode: null,
                    code: null,
                    auditState: null,
                    type: null // 0: 改包装通知单; 1:包装返工单
                }
            };
        },
        methods: {
            onDropdownChange(type, row) {
                if (type === 'query') {
                    if (this.getPermission([`${this.prefix}:${type}`])) {
                        this.onDetailBtn(row);
                    } else {
                        tipsBar(this, 'custom', 'warning', '无操作权限!');
                    }
                } else {
                    if (this.getPermission([`${this.prefix}:${type}`])) {
                        this.onDeleteBtn(row);
                    } else {
                        tipsBar(this, 'custom', 'warning', '无操作权限!');
                    }
                }
            },
            onDeleteBtn(row) {
                this.$msgbox({
                    title: '消息',
                    message: `确认 "删除" ？`,
                    iconClass: 'el-icon-question',
                    showCancelButton: true,
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    beforeClose: (action, instance, done) => {
                        if (action === 'confirm') {
                            instance.confirmButtonLoading = true;
                            instance.confirmButtonText = '执行中...';
                            productionChangeProductRecordDelete({ id: row.id }).then(res => {
                                instance.confirmButtonLoading = false;
                                instance.confirmButtonText = '确定';
                                if (res.data.status === 200) {
                                    tipsBar(this, 'custom', 'success', `删除成功!`);
                                    this.getListRequest();
                                    done();
                                }
                            });
                        } else {
                            done();
                        }
                    }
                });
            },
            onEnableBtn(row) {
                const confList = {
                    0: { name: '下发', api: productionChangeProductRecordConfirm },
                    1: { name: '完成', api: productionChangeProductRecordClose },
                    2: { name: '撤销完成', api: productionChangeProductRecordClearClose }
                };
                this.$msgbox({
                    title: '消息',
                    message: `确认 "${confList[row.auditState].name}" ？`,
                    iconClass: 'el-icon-question',
                    showCancelButton: true,
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    beforeClose: (action, instance, done) => {
                        if (action === 'confirm') {
                            instance.confirmButtonLoading = true;
                            instance.confirmButtonText = '执行中...';
                            confList[row.auditState].api({ id: row.id }).then(res => {
                                instance.confirmButtonLoading = false;
                                instance.confirmButtonText = '确定';
                                if (res.data.status === 200) {
                                    tipsBar(this, 'custom', 'success', `操作成功!`);
                                    this.getListRequest();
                                    done();
                                }
                            });
                        } else {
                            done();
                        }
                    }
                });
            },
            filterColor(list) {
                const arr = list.filter(x => x.auditState);
                const str = arr.map(x => x.name).join(',');
                return str;
            },
            onSearchBtn() {
                this.$set(this.searchParams, 'pageNo', 1);
                this.getListRequest();
            },
            onPageChange(e, size) {
                this.$set(this.searchParams, 'pageNo', e);
                this.$set(this.searchParams, 'pageSize', size);
                this.getListRequest();
            },
            async getDependentData() {
                this.$set(this.searchParams, 'type', this.$route.name === 'PackagingReworkNotice' ? 1 : 0);
                this.workshopList = this.$store.state.user.userWorkshop.workshopList || [];
                const item = this.workshopList.find(x => x.code.toUpperCase() === 'ZL') || {};
                this.$set(this.searchParams, 'workshopId', item.id);
                if (!this.searchParams.belongDate) {
                    // this.$set(this.searchParams, 'belongDate', formatDate(Date.now()));
                }
                this.tableLoading = true;
                await this.getMenuColumnListRequest();
                await this.getListRequest();
                this.tableLoading = false;
            },
            onDetailBtn(e) {
                this.pageType = 'detail';
                this.dataId = e.id;
                this.saveDialogState = true;
            },
            onFinish() {
                this.saveDialogState = false;
                this.getListRequest();
            },
            onVisibleChange(e) {
                this.saveDialogState = e;
                if (!e) {
                    this.dataId = null;
                }
            },
            /** 查询列表 */
            getListRequest() {
                this.tableLoading = true;
                return this.apiItem['page'](this.searchParams).then(res => {
                    this.tableLoading = false;
                    if (res.data.status === 200) {
                        this.tableData = res.data.res;
                        this.totalCount = res.data.count;
                    }
                });
            },
            /** 新增按钮操作 */
            onAddBtn() {
                this.pageType = 'add';
                this.saveDialogState = true;
            },
            /** 修改按钮操作 */
            onEditBtn(row) {
                this.pageType = 'edit';
                this.dataId = row.id;
                this.saveDialogState = true;
            }
        },
        mounted() {
            this.getDependentData();
        }
    };
</script>
